package ru.xpparty.scanner;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicBoolean;

final class SocketOpenner implements Runnable {
	
	private AtomicBoolean isServerPortReady;
	private final int port;

	public SocketOpenner(AtomicBoolean flagOfOpennes, int port) {
		super();
		this.isServerPortReady = flagOfOpennes;
		this.port = port;
	}

	public void run() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = tryAccept();
		} catch (IOException e) {			
			e.printStackTrace();
		} finally {
			tryClose(serverSocket);
		}
	}
	
	private ServerSocket tryAccept() throws IOException {
		ServerSocket serverSocket;
		serverSocket = new ServerSocket(port);
		isServerPortReady.set(true);
		serverSocket.accept();
		return serverSocket;
	}

	private void tryClose(ServerSocket serverSocket) {
		if (serverSocket != null) {
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}